class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int target1 = 0, target2 = 0;
        boolean isDouble = true;
        if ((m + n) % 2 != 0) {
            isDouble = false;
        }
        int pos1 = m / 2;
        int pos2 = n / 2;
        int totalNum = pos1 + pos2 + 2;
        if (m == 0) {
            return isDouble ? (nums2[pos2] + nums2[pos2 - 1]) / 2.0 : nums2[pos2];
        } else if (n == 0) {
            return isDouble ? (nums1[pos1] + nums1[pos1 - 1]) / 2.0 : nums1[pos1];
        }
        int[] result = new int[totalNum];
        int i = 0;
        while (i < totalNum) {
            if (pos1 < 0) {
                result[i++] = nums2[pos2--];
                continue;
            }
            if (pos2 < 0) {
                result[i++] = nums1[pos1--];
                continue;
            }
            if (nums1[pos1] > nums2[pos2]) {
                result[i++] = nums1[pos1];
                pos1--;
            } else {
                result[i++] = nums2[pos2];
                pos2--;
            }
        }

        if (isDouble) {
            target1 = result[totalNum - 1 - (m + n) / 2];
            target2 = result[totalNum - 1 - (m + n) / 2 - 1];
            return (target1 + target2) / 2.0;
        } else {
            target2 = result[totalNum - 1 - (m + n) / 2];
            return target2;
        }

    }
}

//runtime_error:Line 40: java.lang.ArrayIndexOutOfBoundsException: -1
//last_testcase:[1] [1]
